home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 14100 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.1 KB

  1. Path: nntp.teleport.com!usenet
  2. From: GHouck <hksys@teleport.com>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Union type
  5. Date: 11 Apr 1996 20:52:14 GMT
  6. Organization: systems hk
  7. Message-ID: <4kjrdu$3ij@nadine.teleport.com>
  8. References: <4kh43f$h4f@dewey.csun.edu>
  9. NNTP-Posting-Host: ip-pdx09-42.teleport.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 1.22 (Windows; I; 32bit)
  14.  
  15. kc44097@csun.edu (chen) wrote:
  16.  
  17. >union {
  18. >  int   integer;
  19. >  float floating;
  20. >} myUnion;
  21. >
  22. >  myUnion.integer = 1;
  23. >   printf("The value of integer is %d\n",     myUnion.integer);
  24. >   printf("The value of floating is %f\n\n",  myUnion.floating);
  25. >   printf("The value of \"cast\" is %f\n",    (float) myUnion.integer);
  26. >   printf("The value of \"magic\" is %f\n\n", myUnion.integer);
  27. >   printf("The meaning of life ``%d''\n",     (int) myUnion.floating);
  28. >   return (0);
  29. >      The value of integer is 1
  30. >      The value of floating is 0.000000
  31. >      The value of cast is 1.000000
  32. >      The value of magic is 0.000000
  33. >      The meaning of life ``0''
  34. >
  35. >    My question is : Why myUnion.integer is 1 but myUnion.floating is
  36. >    0.000000;Why myUnion.integer change to 0.000000 in 4th printf(),
  37. >    and why myUnion.floating is 0 in 5th printf()?
  38.  
  39. You have to realize that a union of two or more variables shares a common
  40. memory area; there is no conversion between the various types.  So, the
  41. moment you placed a 1 into 'myUnion.integer', you invalidated the floating
  42. point value.  The bit-pattern stored at the location of 'myUnion.integer'
  43. is the bit-pattern for an integer 1.  That pattern (normally) makes no
  44. sense as a floating point number; therefore, the 0.0000's you are getting
  45. (although it could have been some other garbage number).
  46.  
  47. Also, in your printf's you have to remember to print integers with '%d'
  48. or '%ld' formats, and double/floats with '%f' or '%lf' or '%g' formats.
  49. Don't mix them.  That is, you cannot printf a float with a '%d' format
  50. specifier, and vice versa, unless you are trying to perform some sort of
  51. trick.
  52.  
  53. Yours, Geoff Houck
  54.  
  55.  
  56.